package com.example.demo.leetcode.classics150;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _76路径总和
 * @description
 * @date 2023/08/02 14:53
 * <p>
 * ******************************************************
 */
public class _76路径总和 {

    boolean res = false;

    public boolean hasPathSum(TreeNode root, int targetSum) {
        hasPath(root, targetSum);
        return res;
    }

    private void hasPath(TreeNode root, int targetSum) {
        if (root == null) {
            return;
        }
        if(res) {
            return;
        }
        int val = root.val;
        if (root.left == null && root.right == null) {
            if (val == targetSum) {
                res = true;
                return;
            }
        } else {
            if (root.left != null) {
                root.left.val += val;
                hasPath(root.left, targetSum);
            }
            if (root.right != null) {
                root.right.val += val;
                hasPath(root.right, targetSum);
            }
        }

    }


    public static void main(String[] args) {
        TreeNode _7 = new TreeNode(7);
        TreeNode _2 = new TreeNode(2);
        TreeNode _11 = new TreeNode(11, _7, _2);
        TreeNode _44 = new TreeNode(4, _11, null);
        TreeNode _1 = new TreeNode(1);
        TreeNode _4 = new TreeNode(4, null, _1);
        TreeNode _13 = new TreeNode(13);
        TreeNode _8 = new TreeNode(8, _13, _4);
        TreeNode root = new TreeNode(5, _44, _8);
        _76路径总和 s = new _76路径总和();
        System.out.println(s.hasPathSum(root, 22));
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
